package com.lupan.tomcatStudy.springStudy.chapter4_jdbc.dao;

import com.lupan.tomcatStudy.springStudy.common.Student;
import org.springframework.jdbc.core.PreparedStatementCreator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

/**
 * 说明：
 *
 * @author lupan
 * @version 2016/5/17 13:41
 */
public class StudentDao extends BaseDao{



    public List<Student> getAllStudent(){
        //创建数据源
//        DriverManagerDataSource dataSource = new DriverManagerDataSource();
//        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
//        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
//        dataSource.setUsername("root");
//        dataSource.setPassword("root");

        //创建sql执行template
//        JdbcTemplate template = new JdbcTemplate(dataSource);


        //执行sql
        String sql = "select * from student";

        return  template.queryForList(sql,Student.class);
    }

    public void insert(final Student student){
        final String sql = "insert into STUDENT(id,name,num) values(?,?,?)";

        template.update(sql,new Object[]{student.getId(),student.getName(),student.getNum()},new int[]{
            Types.BIGINT, Types.VARCHAR,Types.VARCHAR});

        template.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareCall(sql);
                ps.setLong(1,student.getId());
                ps.setString(2,student.getName());
                ps.setString(3,student.getNum());
                return ps;
            }
        });

    }
}
